package handler.accountFormHandlers;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import other.AssetRegistryFrame;

import builder.FormBuilder;
import builder.FormDirector;
import builder.AccountFormBuilderPackage.AccountFormBuilder;
import builder.AccountFormBuilderPackage.LoginDecorator;

import db.Account;
import db.DBConnector;
import form.AccountForm.AccountForm;

public class RegisterSubmitButtonActionListener implements ActionListener {

	AccountForm registerForm;
    DBConnector db;
    
	public RegisterSubmitButtonActionListener(AccountForm registerForm){
		this.registerForm = registerForm;
		db = new DBConnector();
	}
	
	public void actionPerformed(ActionEvent e) {
	
		String errorMsg = "";
		
		if(registerForm.getInputFormatErrorMsg().isEmpty())
		{
			
			if(doesUsernameExist()){// Username doesn't exist
				if(registerForm.getPassword().getInput().equals(registerForm.getAccountInfoForm().getRetypePassword().getInput())){	// Passwords match							// Password matches
					Account.insertIntoDB(registerForm);
					JOptionPane.showMessageDialog(new JFrame(), "Account has been successfully created.");

					FormBuilder loginbuilder = new AccountFormBuilder();
					loginbuilder = new LoginDecorator(loginbuilder);
					FormDirector logindirector = new FormDirector(loginbuilder);
					logindirector.construct();
					AssetRegistryFrame.getARFrame().changePanel(logindirector.getForm());
					
				}
				else
					errorMsg = "Passwords don't match. Please re-type again.";
			}
			else
				errorMsg = "Username already exists. Please input another username.";
		}
		else
			errorMsg = "Please fill the registration form completely and correctly.";
		
		if(!errorMsg.isEmpty())
			JOptionPane.showMessageDialog(null, errorMsg, "Error!", JOptionPane.WARNING_MESSAGE);
	}
		
	private boolean doesUsernameExist(){
		Account account = Account.createAccount(registerForm.getUserName().getInput());
		if(account == null) //account doesn't exist
			return true;
		
		return false;
	}

}
